package com.sk.weichat.ui.me;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.broadcast.MsgBroadcast;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.UserDao;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.helper.LoginHelper;
import com.sk.weichat.helper.SharedPreferenceHelper;
import com.sk.weichat.sp.UserSp;
import com.sk.weichat.ui.account.MultiAccountHelper;
import com.sk.weichat.ui.account.SMSLoginActivity;
import com.sk.weichat.ui.account.SetPasswordActivity;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.lock.DeviceLockHelper;
import com.sk.weichat.util.AsyncUtils;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.DeviceInfoUtil;
import com.sk.weichat.util.DisplayUtil;
import com.sk.weichat.util.GetFileSizeUtil;
import com.sk.weichat.util.Md5Util;
import com.sk.weichat.util.PreferenceUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.util.UiUtils;
import com.sk.weichat.view.SelectionFrame;
import com.sk.weichat.view.SelectionFrameDialog;
import com.umeng.analytics.MobclickAgent;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 设置
 */
public class SettingActivity extends BaseActivity implements View.OnClickListener {

    private TextView mCacheTv;
    private TextView cacheTv, clearRecordsTv, privateTv, aboutTv;
    private Button mExitBtn;
    private String mLoginUserId;
    private My_BroadcastReceiver mMyBroadcastReceiver = new My_BroadcastReceiver();
    private TextView mTvVersion;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        getSupportActionBar().hide();
        findViewById(R.id.mergerStatus).setBackgroundColor(ContextCompat.getColor(this, R.color.white));
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView tvTitle = (TextView) findViewById(R.id.tv_title_center);
        tvTitle.setText(InternationalizationHelper.getString("JXSettingVC_Set"));

        mLoginUserId = coreManager.getSelf().getUserId();
        initView();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(com.sk.weichat.broadcast.OtherBroadcast.SEND_MULTI_NOTIFY);
        intentFilter.addAction(com.sk.weichat.broadcast.OtherBroadcast.NO_EXECUTABLE_INTENT);
        registerReceiver(mMyBroadcastReceiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        if (mMyBroadcastReceiver != null) {
            unregisterReceiver(mMyBroadcastReceiver);
        }
        super.onDestroy();
    }

    private void initView() {
        cacheTv = (TextView) findViewById(R.id.cache_text);
        mCacheTv = (TextView) findViewById(R.id.cache_tv);
        clearRecordsTv = (TextView) findViewById(R.id.tv_cencel_chat);
        privateTv = (TextView) findViewById(R.id.privacySetting_text);
        aboutTv = (TextView) findViewById(R.id.aboutUs_text);
        mTvVersion = (TextView) findViewById(R.id.tv_setting_version);

        long cacheSize = GetFileSizeUtil.getFileSize(new File(MyApplication.getInstance().mAppDir));
        mCacheTv.setText(GetFileSizeUtil.formatFileSize(cacheSize));
        mTvVersion.setText(DeviceInfoUtil.getVersionName(mContext));

        findViewById(R.id.layout_setting_clear_cache).setOnClickListener(this);
        findViewById(R.id.layout_setting_general).setOnClickListener(this);
        findViewById(R.id.layout_setting_private).setOnClickListener(this);
        findViewById(R.id.layout_setting_safety).setOnClickListener(this);
        findViewById(R.id.layout_setting_about_us).setOnClickListener(this);
        findViewById(R.id.layout_setting_exit).setOnClickListener(this);
        findViewById(R.id.layout_message_notification).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if (!UiUtils.isNormalClick(v)) {
            return;
        }
        switch (v.getId()) {
            case R.id.layout_setting_clear_cache:
                // 清除缓存
                clearCache();
                break;
            case R.id.layout_setting_general:
                // 通用
                startActivity(new Intent(this, SettingGeneralActivity.class));
                break;
            case R.id.layout_setting_private:
                // 隐私设置
                startActivity(new Intent(mContext, PrivacySettingActivity.class));
                break;
            case R.id.layout_setting_safety:
                // 账号与安全
                startActivity(new Intent(mContext, SettingSafetyActivity.class));
                break;
            case R.id.layout_message_notification:
                //消息通知
                startActivity(new Intent(mContext, MessageNotificationActivity.class));
                break;
            case R.id.layout_setting_about_us:
                // 关于我们
                startActivity(new Intent(mContext, AboutActivity.class));
                break;
            case R.id.layout_setting_exit:
                // 退出账号
                if (coreManager.getSelf().getHavePassword() == 0) {//未设置密码
                    showSetPasswordDialog();
                } else {
                    showExitDialog();
                }

                break;
        }
    }

    /**
     * 清楚缓存
     */
    private void clearCache() {
        String filePath = MyApplication.getInstance().mAppDir;
        new ClearCacheAsyncTaska(filePath).execute(true);
    }

    // 去设置密码
    private void showSetPasswordDialog() {
        SelectionFrame setPasswordDialog = new SelectionFrame(this);
        setPasswordDialog.setSomething(getString(R.string.dialog_title), getString(R.string.sure_set_password), "暂不设置", "确定", new SelectionFrame.OnSelectionFrameClickListener() {
            @Override
            public void cancelClick() {//做退出账号操作
                showExitDialog();
            }

            @Override
            public void confirmClick() {
                Intent intent = new Intent(mContext, SetPasswordActivity.class);
                intent.putExtra("from", SetPasswordActivity.SET_FROM_NEW);
                startActivity(intent);
            }
        });
        setPasswordDialog.show();
//        final WindowManager.LayoutParams params = setPasswordDialog.getWindow().getAttributes();
//        params.width = DisplayUtil.dip2px(this,256);
//        setPasswordDialog.getWindow().setAttributes(params);
    }

    // 退出当前账号
    private void showExitDialog() {
        SelectionFrame mSF = new SelectionFrame(this);
        mSF.setSomething(getString(R.string.dialog_title), getString(R.string.sure_exit_account), new SelectionFrame.OnSelectionFrameClickListener() {
            @Override
            public void cancelClick() {

            }

            @Override
            public void confirmClick() {
                //y友盟登出
                MultiAccountHelper.setAddAccountFlag(false);
                MobclickAgent.onProfileSignOff();

                logout();

            }
        });
        mSF.show();
//        final WindowManager.LayoutParams params = mSF.getWindow().getAttributes();
//        params.width = DisplayUtil.dip2px(this,256);
//        mSF.getWindow().setAttributes(params);
    }

    private void logout() {
        if (!DialogHelper.isShowing()) {
            DialogHelper.showMessageProgressDialog(this,"正在退出...");
        }
        HashMap<String, String> params = new HashMap<String, String>();
        // 得到电话
        String phoneNumber = coreManager.getSelf().getTelephone();
        // 去掉区号,
        String mobilePrefix = String.valueOf(PreferenceUtils.getInt(MyApplication.getContext(), Constants.AREA_CODE_KEY, 86));
        String phoneNumberRel;
        if (phoneNumber.startsWith(mobilePrefix)) {
            phoneNumberRel = phoneNumber.substring(mobilePrefix.length());
        } else {
            phoneNumberRel = phoneNumber;
        }
        String digestTelephone = Md5Util.toMD5(phoneNumberRel);
        params.put("telephone", digestTelephone);
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        // 默认为86
        params.put("areaCode", String.valueOf(86));
        params.put("deviceKey", "android");

        HttpUtils.get().url(coreManager.getConfig().USER_LOGOUT)
                .params(params)
                .build()
                .execute(new BaseCallback<String>(String.class) {

                    @Override
                    public void onResponse(ObjectResult<String> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode()==1){

                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    //y友盟登出
                                    MobclickAgent.onProfileSignOff();
                                    // 退出时清除设备锁密码，
                                    DeviceLockHelper.clearPassword();
                                    UserSp.getInstance(mContext).clearUserInfo();
                                    MyApplication.getInstance().mUserStatus = LoginHelper.STATUS_USER_SIMPLE_TELPHONE;
                                    coreManager.logout();
                                    LoginHelper.broadcastLogout(mContext);
                                }
                            }).start();
                            startActivity(new Intent(mContext, SMSLoginActivity.class));
                            finish();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();

                    }
                });
    }

    private class ClearCacheAsyncTaska extends AsyncTask<Boolean, String, Integer> {

        private File rootFile;
        private ProgressDialog progressDialog;

        private int filesNumber = 0;
        private boolean canceled = false;
        private long notifyTime = 0;

        public ClearCacheAsyncTaska(String filePath) {
            this.rootFile = new File(filePath);
        }

        @Override
        protected void onPreExecute() {
            filesNumber = GetFileSizeUtil.getFolderSubFilesNumber(rootFile);
            progressDialog = new ProgressDialog(mContext);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setIndeterminate(false);
            progressDialog.setCancelable(true);
            progressDialog.setMessage(getString(R.string.deleteing));
            progressDialog.setMax(filesNumber);
            progressDialog.setProgress(0);
            // 设置取消按钮
            progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, InternationalizationHelper.getString("JX_Cencal"), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int i) {
                    canceled = true;
                }
            });
            progressDialog.show();
        }

        /**
         * 返回true代表删除完成，false表示取消了删除
         */
        @Override
        protected Integer doInBackground(Boolean... params) {
            if (filesNumber == 0) {
                return 0;
            }
            // 是否删除已清空的子文件夹
            boolean deleteSubFolder = params[0];
            return deleteFolder(rootFile, true, deleteSubFolder, 0);
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
            // String filePath = values[0];
            int progress = Integer.parseInt(values[1]);
            // progressDialog.setMessage(filePath);
            progressDialog.setProgress(progress);
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            progressDialog.dismiss();
            if (!canceled && result == filesNumber) {
                ToastUtil.showToast(mContext, R.string.clear_completed);
            }
            long cacheSize = GetFileSizeUtil.getFileSize(rootFile);
            mCacheTv.setText(GetFileSizeUtil.formatFileSize(cacheSize));
        }

        /**
         * 是否删除完毕
         *
         * @param file
         * @param deleteSubFolder
         * @return
         */
        private int deleteFolder(File file, boolean rootFolder, boolean deleteSubFolder, int progress) {
            if (file == null || !file.exists() || !file.isDirectory()) {
                return 0;
            }
            File flist[] = file.listFiles();
            for (File subFile : flist) {
                if (canceled) {
                    return progress;
                }
                if (subFile.isFile()) {
                    subFile.delete();
                    progress++;
                    long current = System.currentTimeMillis();
                    if (current - notifyTime > 200) {// 200毫秒更新一次界面
                        notifyTime = current;
                        publishProgress(subFile.getAbsolutePath(), String.valueOf(progress));
                    }
                } else {
                    progress = deleteFolder(subFile, false, deleteSubFolder, progress);
                    if (deleteSubFolder) {
                        subFile.delete();
                    }
                }
            }
            return progress;
        }
    }

    private class My_BroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (!TextUtils.isEmpty(action)) {
                if (action.equals(com.sk.weichat.broadcast.OtherBroadcast.SEND_MULTI_NOTIFY)) {// 群发消息结束，关闭当前界面
                    finish();
                } else if (action.equals(com.sk.weichat.broadcast.OtherBroadcast.NO_EXECUTABLE_INTENT)) {// 无可执行的intent 需提醒用户
                    DialogHelper.tip(SettingActivity.this, getString(R.string.no_executable_intent));
                }
            }
        }
    }
}
